﻿using System;
using System.IO;
using System.Data.SqlClient;
using System.Linq;
using System.Windows.Forms;

namespace Estimate
{
    public partial class formLogin : Form
    {
        const string CONNECTION_FILE_NAME = "connect.key";
        string fileName{get{return Application.StartupPath+"//"+CONNECTION_FILE_NAME ;}}

        string connectionString = "";

        Root root;

        public formLogin(Root root)
        {
            this.root = root;
            //root.ConnectionString = 
            
           
            InitializeComponent();
            this.Text = String.Format(" {0} [Ver {1}]", Application.ProductName, Application.ProductVersion);
            this.Icon = Estimate.Properties.Resources.MainIcon;
            this.AcceptButton = buttonLogin;
            

            InitLoginForm();
        }

        private void InitLoginForm()
        {
            tabControl.SelectTab(tabPageLogin);
            connectionString = GetConnectionString();
            if (!CheckConnection(connectionString)) { InitDBConfigureForm(); return; }
            
            root.ConnectionString = connectionString;
            LoadUsers();
        }

        SqlConnection connection;
        private bool  CheckConnection(string connectionString)
        {
            try
            {
                connection = new SqlConnection(connectionString);
                connection.Open();
            }
            catch { return false; }
            return true;
        }

        private void LoadUsers()
        {
            var result = from p in root.Context.Users select p;
            comboBoxUser.DataSource = result.ToArray();
            comboBoxUser.DisplayMember = "login";
        }

        private void InitDBConfigureForm()
        {
            tabControl.SelectTab(tabPageConfigureDB);
            if (connection != null)
            {
                textBoxServer.Text = connection.DataSource;
                textBoxDB.Text = connection.Database;
            }
        }

        private string GetConnectionString()
        {
            string returnValue = "";
            try
            {
                FileStream streem = new FileStream(fileName, FileMode.Open);
                StreamReader reader = new StreamReader(streem);
                returnValue = reader.ReadLine();
                reader.Close(); streem.Close();
            }
            catch { }
            return returnValue;
        }

        private void buttonDBSave_Click(object sender, EventArgs e)
        {
            string connectionString = String.Format(@"Data Source={0};Initial Catalog={1};User ID=sa;password={2}",
                textBoxServer.Text, textBoxDB.Text, textBoxSA.Text);
            if (!CheckConnection(connectionString)) { formMain.ShowError("Помилка Підключення"); return; }
            this.connectionString = connectionString;
            SaveFile();
            InitLoginForm();
        }

        private void SaveFile()
        {
            try
            {
                FileStream streem = new FileStream(fileName, FileMode.Create);
                StreamWriter writer = new StreamWriter(streem);
                writer.WriteLine(connectionString);
                writer.Close(); streem.Close();
            }
            catch { formMain.ShowError("Помилка Запису в Файл " + fileName); return; }
        }

        private void buttonLogin_Click(object sender, EventArgs e)
        {
            User user = (User)comboBoxUser.SelectedValue;
            string password = user.password;
            if (password != textBoxPassword.Text) {formMain.ShowError("Невірний Пароль");return; }
            int rule = user.UserRuleID;
            root.ConnectionState = ConnectionStates.Open;
            switch (rule)
            {
                case 1: root.UserRule = UserRules.Admin; break;
                case 2: root.UserRule = UserRules.Trader; break;
                default: root.ConnectionState = ConnectionStates.Close; break;
            }
            Close();
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl.SelectedTab == tabPageConfigureDB) InitDBConfigureForm();
        }

        
    }
}
